//
//  NSObject+Swizzling.m
//  DemoTool
//
//  Created by iOS on 2018/2/22.
//  Copyright © 2018年 iOS. All rights reserved.
//

#import "NSObject+Swizzling.h"
#import <objc/message.h>

@implementation NSObject (Swizzling)
+ (void)swizzleSelector:(SEL)originalSelector withSwizzledSelector:(SEL)swizzledSelector
{
    Class class = [self class];
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    //可能方法不在这个类中,可能在父类中,因此尝试添加方法实现,否则会崩溃
    BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    //尝试添加方法实现成功则替换方法
    if (didAddMethod) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {//尝试添加方法实现失败,说明已经存在这个方法,则可以直接交换方法的实现
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

@end
